/**
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.apache.hadoop.hive.ql.parse;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hive.ql.exec.Task;
import org.apache.hadoop.hive.ql.exec.mr3.MR3Graph;
import org.apache.hadoop.hive.ql.exec.mr3.MR3Graph.Node;
import org.apache.hadoop.hive.ql.exec.mr3.MR3Log;
import org.apache.hadoop.hive.ql.hooks.ReadEntity;
import org.apache.hadoop.hive.ql.hooks.WriteEntity;
import org.apache.hadoop.hive.ql.plan.MoveWork;

public class MR3Compiler extends MapReduceCompiler {

	protected final Log LOG = LogFactory.getLog(MR3Compiler.class);

	public MR3Compiler() {
		super();
	}

	@Override
	protected void generateTaskTree(List<Task<? extends Serializable>> rootTasks,
			ParseContext pCtx, List<Task<MoveWork>> mvTask, Set<ReadEntity> inputs,
			Set<WriteEntity> outputs) throws SemanticException {

		// generate a graph of MR tasks
		super.generateTaskTree(rootTasks, pCtx, mvTask, inputs, outputs);

		// write dag to log
		try {
			MR3Graph dag = generateGraph(rootTasks);
			// System.err.println(dag.generateGraphViz());
			dag.save("test.dot");
			new MR3Log(dag.generateGraphViz()).run();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// generate graph of tasks
	private MR3Graph generateGraph(List<Task<? extends Serializable>> tasks) {
		MR3Graph dag = new MR3Graph("test");
		for (Task<? extends Serializable> t : tasks) {
			String s = t.getId() + "_" + t.getClass().getSimpleName();
			Node n = dag.getNode(t.getId());
			n.setLabel(s);
			dag = addChildsOfGraph(dag, n, t.getChildTasks());
		}
		return dag;
	}

	private MR3Graph addChildsOfGraph(MR3Graph dag, Node parent,
			List<Task<? extends Serializable>> childTasks) {
		if (childTasks != null)
			for (Task<? extends Serializable> t : childTasks) {
				String s = t.getId() + "_" + t.getClass().getSimpleName();
				Node n = dag.getNode(t.getId());
				n.setLabel(s);
				parent.addEdge(n, "input=, output=");
				dag = addChildsOfGraph(dag, n, t.getChildTasks());
			}
		return dag;
	}
}
